package com.ctyon.watchmanager.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.launcher.ARouter;
import com.ctyon.common.config.glid.GlideImageLoader;
import com.ctyon.common.event.AddWatch;
import com.ctyon.common.event.ChangeWatch;
import com.ctyon.common.event.HeartMessageEvent;
import com.ctyon.common.event.LocationMessageEvent;
import com.ctyon.common.event.RemoveWatch;
import com.ctyon.common.util.DataUtil;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.databinding.FragmentHomeBinding;
import com.ctyon.watchmanager.model.net.entity.Watch;
import com.ctyon.watchmanager.present.HomePresenter;
import com.ctyon.watchmanager.service.BgService;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.ctyon.watchmanager.ui.activity.MainActivity;
import com.ctyon.watchmanager.viewmodel.HomeViewModel;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProviders;
import io.reactivex.Observable;
import lee.com.mqttlibrary.mqtt.MQTTManager;

import static com.ctyon.common.container.ARouterPath.ROUTER_ACTIVITY_BUSINESS;
import static com.ctyon.common.container.ARouterPath.ROUTER_ACTIVITY_CHAT;
import static com.ctyon.common.container.ARouterPath.ROUTER_ACTIVITY_CONTAINER;
import static com.ctyon.watchmanager.service.BgService.TYPE_MQTT;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.PARAM1;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.PARAM2;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.PARAM3;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.PARAM4;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.TAB_INDEX_PARAM;

/**
 * CreateDate：19-6-25 on 上午9:13
 * Describe:
 * Coder: lee
 */
public class HomeFragment extends BaseFragment {

    public static final String TAG = "HomeFragment";

    private HomeViewModel mViewModel;
    private FragmentHomeBinding mBinding;
    private String lon, dim;

    public static HomeFragment newInstance() {
        final HomeFragment fragment = new HomeFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Logger.d("onCreateView");
        EventBus.getDefault().register(this);

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);

        mBinding.setHomePresenter(homePresenter);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Logger.d("onActivityCreated");
        mViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);

        subscribeBanner(mViewModel.getBanner());
        subscribeWatch(mViewModel.getWatch());

        mBinding.homeBanner.setImageLoader(new GlideImageLoader());
        mBinding.homeBanner.setDelayTime(5000);
        mViewModel.initBanner();

        initData();
    }

    public void initData() {
        mViewModel.initWatch();
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onChangeWatch(ChangeWatch changeWatch) {
        initData();
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onAddWatch(AddWatch addWatch) {
        Logger.d("onAddWatch");
        mViewModel.initWatch();
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onRemoveWatch(RemoveWatch removeWatch) {
        Logger.d("onRemoveWatch");
        mViewModel.initWatch();
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onHeartBeat(HeartMessageEvent messageEvent) {
        mBinding.setBattery(messageEvent.getBattery() + "%");
        refreshBattery(Integer.valueOf(messageEvent.getBattery()));
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onLocation(LocationMessageEvent messageEvent) {
        mBinding.setLocation(messageEvent.getLocation());
        mBinding.setLocationTime(DataUtil.getDateToString(messageEvent.getTime(), "HH:mm:ss"));
        lon = messageEvent.getLon();
        dim = messageEvent.getDim();
    }

    private void subscribeBanner(LiveData<List<Integer>> liveData) {
        liveData.observe(this, (banners) -> {
            Logger.d("subscribeBanner : " + banners);
            if (banners != null) {
                mBinding.homeBanner.setImages(banners);
                mBinding.homeBanner.start();
            }
            mBinding.executePendingBindings();
        });
    }

    private void subscribeWatch(LiveData<Watch> liveData) {
        liveData.observe(this, (watch) -> {
            Logger.d("subscribeWatch : " + watch);
            if (watch != null) {
                if (DataUtil.isEmptyOr(watch.getMeid())) {
                    Logger.d("setIsEmpty");
                    mBinding.setIsEmpty(true);
                } else {
                    Logger.d("setWatch");
                    mBinding.setIsEmpty(false);
                    BasicApp.getInstance().setWatch(watch);
                    loadData();
                    if (!MQTTManager.getInstance().isConnect()) {
                        MQTTManager.getInstance()
                                .init(BasicApp.getInstance().getApplicationContext()
                                        , String.valueOf(BasicApp.getInstance().getManager().getManagerId())
                                        , watch.getMeid())
                                .bindMQTTService();
                        Observable.timer(5, TimeUnit.SECONDS).subscribe(aLong -> {
                            BgService.watchMqtt(BasicApp.getInstance().getApplicationContext(), TYPE_MQTT);
                        });
                    }
                }
            } else {
                Logger.d("setIsEmpty");
                mBinding.setIsEmpty(true);
            }
            mBinding.executePendingBindings();
        });
    }

    private final HomePresenter homePresenter = new HomePresenter() {
        @Override
        public void onLocationClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, MapFragment.TAG)
                    .withString(PARAM1, lon)
                    .withString(PARAM2, dim)
                    .navigation();
        }

        @Override
        public void onFamilyChatClick() {
//            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
//                    .withString(TAB_INDEX_PARAM, ChatFragment.TAG)
//                    .navigation();

            ARouter.getInstance().build(ROUTER_ACTIVITY_CHAT)
                    .navigation();
        }

        @Override
        public void onVoiceProtectClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, VoiceFragment.TAG)
                    .navigation();
        }

        @Override
        public void onContactsClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, ContactsFragment.TAG)
                    .navigation();
        }

        @Override
        public void onFindDeviceClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, FindFragment.TAG)
                    .navigation();
        }

        @Override
        public void onMoreClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_BUSINESS)
                    .navigation();
        }

        @Override
        public void onExchangeClick() {
            ((MainActivity) getActivity()).openDrawer();
        }

        @Override
        public void onAddClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, AddWatchFragment.TAG)
                    .navigation();
        }

        @Override
        public void onIconClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, WatchFragment.TAG)
                    .navigation();
        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Logger.d("onHiddenChanged : " + hidden);
        if (hidden) {
            mBinding.homeBanner.stopAutoPlay();
        } else {
            mBinding.homeBanner.startAutoPlay();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Logger.t(LTAG).d(" [ onResume ]");
        mBinding.homeBanner.startAutoPlay();
        loadData();
    }

    @Override
    public void onPause() {
        super.onPause();
        Logger.d("onPause");
        mBinding.homeBanner.stopAutoPlay();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.t(this.getClass().getName()).d("onDestroy");
        mBinding.homeBanner.releaseBanner();
        EventBus.getDefault().unregister(this);
    }

    private void refreshBattery(int battery) {
        if (battery <= 5){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery0));
        } else if (battery <= 15){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery1));
        }else if (battery <= 40){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery2));
        }else if (battery <= 60){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery3));
        }else if (battery <= 80){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery4));
        }else if (battery <= 100){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery5));
        }
    }

    private void loadData() {
        if (null == BasicApp.getInstance().getWatch()) {
            return;
        }
        if (0 < BasicApp.getInstance().getWatch().getLocationTime()) {
            mBinding.setLocationTime(DataUtil.getDateToString(BasicApp.getInstance().getWatch().getLocationTime(), "HH:mm:ss"));
        }
        mBinding.setNick(BasicApp.getInstance().getWatch().getNick());
        int battery = BasicApp.getInstance().getWatch().getBattery();
        mBinding.setBattery(battery + "%");
        refreshBattery(battery);
        mBinding.setLocation(BasicApp.getInstance().getWatch().getLocation());
    }

}
